#ifndef _DatasetIO_dataset_io_utils_H_
#define _DatasetIO_dataset_io_utils_H_

#include <algorithm>
#include <iostream>
#include <vector>

namespace DatasetIO {

static int compare_timestamp(const std::vector<double> &timestamps) {
    return std::max_element(timestamps.begin(), timestamps.end()) -
           timestamps.begin();
}

static bool timestamp_comp(std::pair<double, int> ti,
                           std::pair<double, int> tj) {
    return (ti.first < tj.first);
}

template <class T>
inline std::vector<T> find_closest_elements(const std::vector<T> &arr,
                                            const size_t &k, const T &x) {
    if (arr.size() < k || arr.size() == 0 || k <= 0)
        return std::vector<T>();

    size_t l = 0;
    size_t r = arr.size() - k;
    while (l < r) {
        size_t m = (l + r) / 2;
        if (x - arr[m] > arr[m + k] - x)
            l = m + 1;
        else
            r = m;
    }

    return std::vector<T>(arr.begin() + l, arr.begin() + k + l);
}

template <class T>
inline std::vector<size_t> find_closest_index(const std::vector<T> &arr,
                                              const size_t &k, const T &x) {
    if (arr.size() < k || arr.size() == 0 || k <= 0)
        return std::vector<size_t>();

    size_t l = 0;
    size_t r = arr.size() - k;
    while (l < r) {
        size_t m = (l + r) / 2;
        if (x - arr[m] > arr[m + k] - x)
            l = m + 1;
        else
            r = m;
    }

    std::vector<size_t> index;
    for (size_t i = 0; i < k; i++) {
        index.push_back(l + i);
    }

    return index;
}

}  // namespace DatasetIO

#endif